package com.hubu.string;

public class StringCoder {
    public String  encode(String source){
        //aabcccddddeee
        char before=source.charAt(0);
        StringBuilder stringBuilder=new StringBuilder();
        int count=1;
        for(int i=1;i<source.length();i++){
            char item=source.charAt(i);
            if(item==before){
                count++;
            }
            else{
                if(count>1){
                    stringBuilder.append(count);
                }
                stringBuilder.append(before);
                before=item;
                count=1;
            }
        }
        //拼接上最后一个
        if(count>1){
            stringBuilder.append(count);
        }
        stringBuilder.append(before);
        return stringBuilder.toString();
    }

    public String decode(String source){
        //2ab3c4d3e
        if(source==null||"source".equals("")){
            throw new RuntimeException("source is invalide");
        }
        //用于记录数字
        String number="";
        StringBuilder stringBuilder=new StringBuilder();
        for(int i=0;i<source.length();i++){
            //校验当前位是不是数组为
            char item=source.charAt(i);
            if(item>='0'&&item<='9'){
                number=number+item;
                //看下一位是不是数字字符
                if(i<source.length()-1){
                    char next=source.charAt(i+1);
                    if(next<'0'||next>'9'){
                        //当前统计完毕
                        int n=Integer.parseInt(number);
                        for(int j=0;j<n;j++){
                            stringBuilder.append(next);
                        }
                        number="";
                    }
                }
            }
        }
        return stringBuilder.toString();
    }
}
